package org.damazio.flight.checklists.data;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

public class CheckListItemsTable {

  public static final String TABLE_NAME = "checklist_items";
  private static final String CREATE_TABLE_SQL =
      "CREATE TABLE IF NOT EXISTS checklist_items" +
          "(item_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
          " parent_id INTEGER NOT NULL REFERENCES checklists(list_id) ON DELETE CASCADE," +
          " ordered INTEGER NOT NULL," +
          " name VARCHAR(255) NOT NULL," +
          " completed BOOL DEFAULT FALSE);";
  public static final String ITEM_ID_COLUMN = "item_id";
  public static final String COMPLETED_COLUMN = "completed";

  public static final String QUERY_SQL =
      "SELECT " + ITEM_ID_COLUMN + " as " + CheckListsSchema.ID_COLUMN + "," +
      "'" + CheckListsSchema.ITEM_TYPE + "' as " + CheckListsSchema.TYPE_COLUMN + "," +
      CheckListsSchema.NAME_COLUMN + "," +
      CheckListsSchema.ORDERED_COLUMN + "," +
      CheckListsSchema.PARENT_ID_COLUMN +
      " FROM " + TABLE_NAME;

  private final SQLiteDatabase db;

  CheckListItemsTable(SQLiteDatabase db) {
    this.db = db;
  }

  public void create() {
    db.execSQL(CREATE_TABLE_SQL);
  }

  public long insert(String name, long parentId) {
    ContentValues values = new ContentValues();
    values.put(CheckListsSchema.PARENT_ID_COLUMN, parentId);
    values.put(CheckListsSchema.ORDERED_COLUMN, 1);  // TODO: real ordering
    values.put(CheckListsSchema.NAME_COLUMN, name);

    return db.insertOrThrow(TABLE_NAME, null, values);
  }

  public void markCompleted(long itemId, boolean completed) {
    ContentValues values = new ContentValues();
    values.put(COMPLETED_COLUMN, completed);
    db.update(TABLE_NAME, values ,
        ITEM_ID_COLUMN + "=?", new String[] { Long.toString(itemId) });
  }

  public void delete(long itemId) {
    db.delete(TABLE_NAME, ITEM_ID_COLUMN + "=?", new String[] { Long.toString(itemId) });
  }
}
